
#include <BTextEdit>
#include <BYamlDocument>
#include <BStyle>

#include "YamlFormat.h"

YamlFormat::YamlFormat(const BString& name) : BTextFormat(name)
{
	_dockLayout = new BDockLayout();
	_dockLayout->setPart(Part_Center);
	_dockLayout->setSplitable(true);
	_dockLayout->setSpacing(5);
	_treeWidget = new BTreeWidget();
	_treeWidget->setWidthPolicy(Policy_Preferred | Policy_Expanding);
	_dockLayout->addWidget(_treeWidget, Align_RightTop);
	_dockLayout->setStretch(_treeWidget, BSizeStretch(1, 50));

}
YamlFormat::~YamlFormat()
{

}

BTreeItem* YamlFormat::createTreeItem(BYamlNode* node)
{
	const BStyle* realStyle = _treeWidget->realStyle();
	BTreeItem* item = new BTreeItem(node->name());
	item->setAsset(node);
	if (node->text().size())
	{
		BString text = node->text();
		if (text.isNumber())
		{
			if (text.contain('.'))
				if (text.endWith('f'))
					node->setAsset(text.toFloat());
				else
					node->setAsset(text.toDouble());
			else
				node->setAsset(text.toInt());
		}
		else
		{

		}
		if (node->asset().is<float>())
			item->setImage(realStyle->image("float"));
		else if (node->asset().is<double>())
			item->setImage(realStyle->image("double"));
		else if (node->asset().is<int>())
			item->setImage(realStyle->image("int"));
		else if (node->asset().is<BString>())
			item->setImage(realStyle->image("string"));
		else
			item->setImage(realStyle->image("unknown"));
	}
	else
	{
		item->setImage(realStyle->image("empty"));
	}
	for (int i = 0; i < node->childCount(); i++)
	{
		BTreeItem* child = createTreeItem(node->child(i));
		item->addChild(child);
	}
	return item;
}

void YamlFormat::attached(BTextEdit* textEdit)
{
	_dirty = true;
	_treeWidget->clearItems();
	textEdit->addLayout(_dockLayout);
}
void YamlFormat::detached(BTextEdit* textEdit)
{
	_dirty = false;
	_treeWidget->clearItems();
	textEdit->removeLayout(_dockLayout);
}

void YamlFormat::freshEvent(const BEvent& event)
{
	BTextEdit* textEdit = this->textEdit();
	if (_dirty && textEdit)
	{
		BYamlDocument document;
		BYamlNode* node = document.read(textEdit->text());
		_treeWidget->clearItems();
		for (int i = 0; i < document.nodeCount(); i++)
		{
			BTreeItem* item = createTreeItem(document.node(i));
			_treeWidget->addTopItem(item);
		}
		_dirty = false;
	}
}
